from django.shortcuts import render
from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.conf import settings
import requests
import json
from .wechat_api import WeChatAPI  # 导入我们创建的微信API工具类

# Create your views here.
def hello_page(request):
    html = "<h1>这是一个页面<h1>"
    return HttpResponse(html, content_type='text/html;charset=utf-8', status=200)

class WechatLoginView(APIView):
    """
    微信小程序登录API
    通过设置 authentication_classes 和 permission_classes 为空来禁用认证
    这样就不需要 CSRF token 了
    """
    authentication_classes = [] # 关键：禁用所有认证
    permission_classes = []     # 关键：禁用所有权限检查
    
    def post(self, request):
        # print(request.data) # {'code': '0d1OXlll2MYklg4iOpml2lLg4n3OXlll'}
        code = request.data.get('code')
        if not code:
            return Response({'error': '缺少code参数'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 字符串前的f表示f-string，即格式化字符串字面值（Formatted String Literals）
        wechat_url = f'https://api.weixin.qq.com/sns/jscode2session?appid={settings.WECHAT_APPID}&secret={settings.WECHAT_SECRET}&js_code={code}&grant_type=authorization_code'
        
        try:
            response = requests.get(wechat_url)
            data = response.json()
            
            if 'errcode' in data:
                return Response({'error': data['errmsg']}, status=status.HTTP_400_BAD_REQUEST)
            
        except Exception as e:
            return Response({'error': f'登录失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        else:
            openid = data.get('openid')
            session_key = data.get('session_key')
            # unionid = data.get('unionid')
            
            # 这里可以添加用户创建/查询逻辑
            
            return Response({
                'openid': openid,           # 用户唯一标识
                'session_key': session_key, # 会话密钥
                # 'unionid': unionid,       # 用户在开放平台的唯一标识符
                'status': 'success'
            })
        
class SendSubscribeMessageView(APIView):
    """
    发送订阅消息API
    """
    authentication_classes = []
    permission_classes = []
    
    def post(self, request):
        """
        发送订阅消息
        请求数据格式：
        {
            "openid": "用户的openid",
            "template_id": "模板ID",  # 可选，不传则使用默认模板
            "page": "pages/index/index",  # 可选，跳转页面
            "data": {
                "thing1": {"value": "标题内容"},
                "time2": {"value": "2023-12-01 10:00"},
                "thing3": {"value": "详细内容描述"}
            }

            详细内容
            消息发送者  {{thing1.DATA}}
            消息内容    {{thing2.DATA}}
            消息时间    {{time3.DATA}}

        }
        """
        openid = request.data.get('openid')
        template_id = request.data.get('template_id', settings.WECHAT_TEMPLATE_ID)
        page = request.data.get('page')
        data = request.data.get('data')
        
        if not openid:
            return Response({'error': '缺少openid参数'}, status=status.HTTP_400_BAD_REQUEST)
        
        if not data:
            return Response({'error': '缺少data参数'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 发送订阅消息
        result = WeChatAPI.send_subscribe_message(openid, template_id, data, page)
        
        if result.get('errcode') == 0:
            return Response({
                'status': 'success',
                'msg': '发送成功',
                'message_id': result.get('msgid')
            })
        else:
            return Response({
                'status': 'error',
                'error_code': result.get('errcode'),
                'error_msg': result.get('errmsg')
            }, status=status.HTTP_400_BAD_REQUEST)
